package com.functest.jpwise.util;

import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;

import java.util.*;

public class DonutIterator<T> implements Iterator<T> {
    public DonutIterator(Collection<T> tList, boolean isShuffled) {
        super();
        Preconditions.checkArgument(!tList.isEmpty(), "Donut can't be empty!");
        this.baseList = ImmutableList.copyOf(tList);
        this.shuffled = isShuffled;
    }

    public DonutIterator(Collection<T> tList) {
        this(tList, false);
    }

    @Override
    public boolean hasNext() {
        return true;
    }

    @Override
    public T next() {
        if (curIterator.hasNext()) {
            return curIterator.next();
        }

        if (shuffled) {
            ArrayList<T> list = new ArrayList<>(baseList);
            Collections.shuffle(list);
            curIterator = list.iterator();

        } else {
            curIterator = baseList.iterator();
        }

        return ((curIterator.next()));

    }

    @Override
    public void remove() {
        throw new UnsupportedOperationException("Not supported!");
    }

    private final boolean shuffled;
    private final List<T> baseList;
    private Iterator<T> curIterator = new ArrayList<T>().iterator();

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("DonutIterator{");
        sb.append("baseList=").append(baseList);
        sb.append("shuffled?").append(shuffled);
        sb.append('}');
        return sb.toString();
    }
}
